import fetch from 'isomorphic-fetch';
import * as SignUtils from './sign';
import moment from 'moment';

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url, payload) {
  console.log(url, payload);

  let type = 'string';
  const { method,body } = payload;
  if (body != null) {
    type = typeof body;
  }

  const headers = {};
  headers['X-YH-APP'] = 'YHLIB';
  headers.Accept = 'application/json';

  let params = '';
  if (type === 'string') {
    headers['Content-Type'] = 'application/json';
    const timestamp = moment().format('x');
    const sign = SignUtils.get(timestamp, body);
    params = `${url.indexOf('?') > 0 ? '&' : '?'}sign=${sign}&timestamp=${timestamp}`;
  }
  const options = {
    method,
	body,
    headers,
    credentials: 'same-origin'
  };

  let response = null;
  try {
    response = await fetch(url + params, options);
  } catch (e) {
    console.error(e);
    const error = new Error('访问异常');
    throw error;
  }

  const data = await response.json();
  return data.data;

}

